<template>
  <div class="box">
    <div class="left">
      <div class="title">双碳信息录入</div>
      <div class="orders" ref="containerRef">
        <div
          :class="{ order: true, active: state.currentIndex === i }"
          v-for="(o, i) in state.orders"
          @click="
            () => {
              state.currentIndex = i;
              state.activeKey = 0;
            }
          "
        >
          <div class="head">
            <span class="name"
              >{{ o.name }} <i style="color: gray">{{ o.code }}</i></span
            >
            <a-tag :color="!!o.complete ? '#87d068' : '#f50'">{{
              !!o.complete ? "已竣工" : "未竣工"
            }}</a-tag>
          </div>

          <div class="body">
            <span>进厂时间：{{ dayjs(o.enterTime).format("YYYY-MM-DD") }}</span>
            <span>出厂时间：{{ dayjs(o.outTime).format("YYYY-MM-DD") }}</span>
          </div>
        </div>
      </div>
      <div class="page">
        <a-pagination
          :current="state.current"
          :pageSize="state.pageSize"
          :total="state.total"
          :responsive="true"
          show-less-items
          @change="onPageChange"
        />
      </div>
    </div>
    <div class="right">
      <div class="title">
        {{ currentOrder?.name }}
        <a-button
          v-if="currentOrder?.complete === 0"
          size="small"
          @click="overFlow(currentOrder.id)"
          type="primary"
          link
          >竣工</a-button
        >
        <a-button type="link" @click="downloadTemplate">
          <template #icon>
            <download-outlined />
          </template>
          下载模板
        </a-button>
        <a-upload
          :showUploadList="false"
          accept=".xls,.xlsx"
          :customRequest="
            ({ file }) => {
              uploadExcel(file);
            }
          "
          :disabled="disabled"
        >
          <a-button type="link" :disabled="disabled">
            <upload-outlined></upload-outlined>
            上传
          </a-button>
        </a-upload>
      </div>
      <div class="body">
        <a-tabs v-if="!!currentOrder" v-model:activeKey="state.activeKey">
          <a-tab-pane
            :key="i"
            :tab="o.label"
            v-for="(o, i) in currentOrder.workFlowArray"
          >
            <!-- 根据工序加载表单 -->
            <Work
              :complete="currentOrder.complete"
              :workflow="o"
              :orderId="currentOrder.id"
              :shipId="currentOrder.shipId"
            />
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  getCurrentInstance,
  reactive,
  ref,
  onMounted,
  onUnmounted,
  computed,
} from "vue";
import dayjs from "dayjs";
import Work from "./page/work.vue";
import { getValueByLabel } from "@/utils/shipflow/works.js";
import _ from "lodash";

const { proxy } = getCurrentInstance();

const state = reactive({
  orders: [],
  currentIndex: 0,
  current: 1,
  total: 0,
  pageSize: 10,
  activeKey: 0,
});
const containerRef = ref();

const downloadTemplate = () => {
  // 1. 获取当前选中的订单
  const order = state.orders[state.currentIndex];
  if (!order || !order.workFlowArray || order.workFlowArray.length === 0) {
    proxy.$message.warning("当前订单无工序数据");
    return;
  }

  // 2. 获取当前选中的工序（通过 state.activeKey 作为 workFlowArray 的索引）
  const selectedWorkflow = order.workFlowArray[state.activeKey];
  if (!selectedWorkflow) {
    proxy.$message.warning("未找到选中的工序");
    return;
  }

  const workflowLabel = selectedWorkflow.label; // 如 "船体"

  // 3. 获取 type（假设你有地方定义了 state.type，比如表单选择）
  //    如果没有，可以先 mock 或从其他地方获取
  let type = 3;

  if(selectedWorkflow.label == '船体下料'){
    type = '3'
  }else if(selectedWorkflow.label == '船体割旧'){
    type = '4'
  }else if(selectedWorkflow.label == '船体焊接'){
    type = '5'
  }else if(selectedWorkflow.label == '机电焊接'){
    type = '6'
  }else if(selectedWorkflow.label == '拖轮油耗'){
    type = '7'
  }else if(selectedWorkflow.label == '单船'){
    type = '8'
  }else if(selectedWorkflow.label == '高空车'){
    type = '9'
  }else if(selectedWorkflow.label == '舱室及船壳喷漆'){
    type = '10'
  }else if(selectedWorkflow.label == '喷漆房分段喷漆'){
    type = '11'
  }else if(selectedWorkflow.label == '舱室打砂'){
    type = '12'
  }else if(selectedWorkflow.label == '打砂房分段打砂'){
    type = '13'
  }else if(selectedWorkflow.label == '超水除锈'){
    type = '14'
  }else if(selectedWorkflow.label == '移动电箱'){
    type = '15'
  }

  // 4. 构造下载 URL，带上 workflow 和 type
  const url = `http://localhost:8082/api/excel/import/energy?type=${type}`;

  // 5. 创建链接并触发下载
  const link = document.createElement("a");
  link.href = url;
  link.download = `${workflowLabel}能源数据导入模板.xlsx`; // 可选：让浏览器自动命名
  link.style.display = "none";

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const uploadExcel = async (file) => {
  // 1. 文件校验（可选）
  const isExcel =
    file.type === "application/vnd.ms-excel" ||
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

  if (!isExcel) {
    proxy.$message.error("只能上传 Excel 文件（.xls 或 .xlsx）!");
    return false;
  }

  // 限制文件大小（例如 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$message.error("文件大小不能超过 10MB！");
    return false;
  }
  const order = state.orders[state.currentIndex];
 const selectedWorkflow = order.workFlowArray[state.activeKey];
  if (!selectedWorkflow) {
    proxy.$message.warning("未找到选中的工序");
    return;
  }

  const formData = new FormData();
  formData.append("file", file);
  formData.append("shipRepairId", order.id); 
  let api = "";
  if(selectedWorkflow.label == '船体下料'){
    api = "ship_cut/"
  }else if(selectedWorkflow.label == '船体割旧'){
    api = "ship_old/"
  }else if(selectedWorkflow.label == '船体焊接'){
    api = "ship_weld/"
  }else if(selectedWorkflow.label == '机电焊接'){
    api = "machine_pipe/"
  }else if(selectedWorkflow.label == '拖轮油耗'){
    api = "tow_ship_oil/"
  }else if(selectedWorkflow.label == '移动电箱'){
    api = "electric_box/"
  }
  

 
  try {
    // 3. 调用上传接口
    const { success, msg, data } = await proxy.$axios.post(
      "/excel/import/"+api, // 后端上传接口路径
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );

    // 4. 处理响应
    if (success) {
      proxy.$message.success("文件上传成功！");
      // 上传成功后刷新数据
      getOrders(1);
    } else {
      proxy.$message.error(msg || "上传失败，请检查文件内容");
    }
  } catch (error) {
    console.error("上传出错：", error);
    proxy.$message.error("文件上传失败，请稍后重试");
  }
};


const getOrders = (page) => {
  proxy.$axios
    .get("/ship_repair/list", {
      params: { pageNumber: page, pageSize: state.pageSize },
    })
    .then(({ success, data }) => {
      if (success) {
        state.orders = data.content;
        state.total = data.totalElements;
        state.current = page;
      }
    });
};

let resizeObserver = null;
onMounted(() => {
  resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const allHeight = entry.contentRect.height;
      state.pageSize = Math.floor(allHeight / 65.13);
      getOrders(1);
    }
  });
  resizeObserver.observe(containerRef.value);
});

onUnmounted(() => {
  resizeObserver.disconnect();
});

const onPageChange = (page) => {
  getOrders(page);
};

const currentOrder = computed(() => {
  const order = state.orders[state.currentIndex];
  if (order) {
    const array = [];
    if (order.workFlows) {
      const arr = order.workFlows.split(",");
      _.each(arr, (o) => {
        array.push({ label: o, value: getValueByLabel(o) });
      });
    }
    order.workFlowArray = _.sortBy(array, "value");
  }
  return order;
});

const overFlow = (id) => {
  proxy
    .$axios({ method: "put", url: `/ship_repair/complete/${id}` })
    .then(({ success }) => {
      if (success) {
        proxy.$message.success("提交成功");
        getOrders(1);
      }
    });
};
</script>

<style lang="less" scoped>
.box {
  height: 100%;
  display: flex;
  padding: 2px;

  .title {
    border-bottom: 1px solid #fff;
    padding: 6px;
    height: 35px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .left {
    width: 320px;
    height: 100%;
    background: #262626;
    margin-right: 2px;
    padding: 1rem;

    .orders {
      height: calc(100% - 35px - 32px);
      overflow-y: auto;

      .order {
        padding: 8px;
        background-color: #181818;
        margin: 4px 0;
        border: 1px solid transparent;

        .head {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: gray;

          .name {
            width: 75%;
            font-size: large;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            color: #fff;
          }
        }

        .body {
          color: gray;
          font-size: 12px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          span {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            max-width: 50%;
          }
        }

        &:hover {
          .active;
        }
      }

      .active {
        background-color: black;
        cursor: pointer;
        border: 1px solid #177ddc;
      }
    }

    .page {
      display: flex;
      justify-content: center;
    }
  }

  .right {
    width: calc(100% - 320px);
    background: #262626;
    padding: 1rem;

    .body {
      height: calc(100% - 35px);
      overflow-y: auto;
    }
  }
}
</style>
